<script setup>
import { ref } from "vue";
import { ElMessage, ElMessageBox } from "element-plus";
import {
  addBorrowService,
  listBorrowsForStudentsService,
  updateBorrowService,
  deleteBorrowService,
} from "@/api/borrowing.js";
import moment from "moment";
import { updatePaymentStatusService } from "@/api/fine.js";
import { mailService } from "@/api/mail.js";

const borrowsData = ref([]);
const pageNum = ref(1);
const pageSize = ref(15);
const total = ref(10);
const showUpdateDialog = ref(false);
const updateFormRef = ref(null);
const selectedBorrows = ref([]);

const newBorrow = ref({
  borrowingId: "",
  bookId: "",
  userId: "",
  borrowDate: "",
  returnDate: "",
  renewalStatus: "",
  dueDate: "",
  paymentStatus: "",
  fineId: "",
});

const searchBorrow = ref({
  borrowingId: "",
  bookId: "",
  userId: "",
  renewalStatus: "",
  studentName: "",
  studentId: "",
  categoryName: "",
});

const handleSizeChange = (size) => {
  pageSize.value = size;
  listBorrows();
};

const handleCurrentChange = (num) => {
  pageNum.value = num;
  listBorrows();
};

const listBorrows = async () => {
  let params = {
    pageNum: pageNum.value,
    pageSize: pageSize.value,
    ...searchBorrow.value,
  };
  let result = await listBorrowsForStudentsService(params);
  total.value = result.data.total;
  borrowsData.value = result.data.records;
};

const reset = async () => {
  searchBorrow.value = {
    borrowingId: "",
    bookId: "",
    userId: "",
    renewalStatus: "",
    studentName: "",
    studentId: "",
    categoryName: "",
  };
  await listBorrows();
};

const viewUpdate = async (row) => {
  if (updateFormRef.value) {
    updateFormRef.value.resetFields();
  }
  newBorrow.value = { ...row };
  showUpdateDialog.value = true;
};
const updateBorrow = async () => {
  updateFormRef.value.validate(async (valid) => {
    if (valid) {
      let updateResult = await updateBorrowService(newBorrow.value);
      let paymentStatusUpdateResult = { code: 0 };

      if (newBorrow.value.paymentStatus) {
        paymentStatusUpdateResult = await updatePaymentStatusService(
          newBorrow.value.fineId,
          newBorrow.value.paymentStatus,
        );
      }

      if (updateResult.code === 0 && paymentStatusUpdateResult.code === 0) {
        showUpdateDialog.value = false;
        ElMessage.success("更新成功");
        await listBorrows();
      } else {
        ElMessage.error("更新失败");
      }
    }
  });
};

const deleteBorrow = async (borrowingId) => {
  await ElMessageBox.confirm("此操作将永久删除该借阅记录, 是否继续?", "提示", {
    confirmButtonText: "确定",
    cancelButtonText: "取消",
    type: "warning",
  });
  let deleteResult = await deleteBorrowService(borrowingId);
  if (deleteResult.code === 0) {
    ElMessage.success("删除成功");
    await listBorrows();
  } else {
    ElMessage.error("删除失败");
  }
};

const confirmDelete = (borrowingId) => {
  ElMessageBox.confirm("此操作将永久删除该借阅记录, 是否继续?", "提示", {
    confirmButtonText: "确定",
    cancelButtonText: "取消",
    type: "warning",
  })
    .then(() => {
      deleteBorrow(borrowingId);
    })
    .catch(() => {
      ElMessage.info("已取消删除");
    });
};

const handleSelectionChange = (selection) => {
  selectedBorrows.value = selection;
};

const confirmBatchDelete = () => {
  ElMessageBox.confirm("此操作将永久删除选中的借阅记录, 是否继续?", "提示", {
    confirmButtonText: "确定",
    cancelButtonText: "取消",
    type: "warning",
  })
    .then(async () => {
      let successCount = 0;
      let skipCount = 0;
      for (const borrow of selectedBorrows.value) {
        let result = await deleteBorrowService(borrow.borrowingId);
        if (result.code === 0) {
          successCount++;
        } else {
          skipCount++;
        }
      }
      ElMessage.success(`批量删除成功: ${successCount}, 跳过: ${skipCount}`);
      await listBorrows();
    })
    .catch(() => {
      ElMessage.info("已取消批量删除");
    });
};

const confirmExtendDueDates = (days) => {
  ElMessageBox.confirm(
    `此操作将延长选中的借阅记录到期时间${days}天, 是否继续?`,
    "提示",
    {
      confirmButtonText: "确定",
      cancelButtonText: "取消",
      type: "warning",
    },
  )
    .then(async () => {
      let successCount = 0;
      let skipCount = 0;
      for (const borrow of selectedBorrows.value) {
        borrow.dueDate = moment(borrow.dueDate)
          .add(days, "days")
          .format("YYYY-MM-DD");
        let result = await updateBorrowService(borrow);
        if (result.code === 0) {
          successCount++;
        } else {
          skipCount++;
        }
      }
      ElMessage.success(
        `选中的借阅记录到期时间已延长${days}天: 成功: ${successCount}, 跳过: ${skipCount}`,
      );
      await listBorrows();
    })
    .catch(() => {
      ElMessage.info("已取消延期");
    });
};

const formatDate = (row, column, cellValue) => {
  if (!cellValue) return "未归还";
  return moment(cellValue).format("YYYY-MM-DD");
};

const rulesUpdate = {
  bookId: [{ required: true, message: "请输入书籍ID", trigger: "blur" }],
  userId: [{ required: true, message: "请输入用户ID", trigger: "blur" }],
  borrowDate: [
    { required: true, message: "请选择借阅日期", trigger: "change" },
  ],
  dueDate: [{ required: true, message: "请选择到期日期", trigger: "change" }],
};

const statusCellStyle = ({ row, column }) => {
  if (column.property === "returnDate") {
    if (row.returnDate && moment(row.returnDate).isAfter(row.dueDate)) {
      return { backgroundColor: "rgba(247, 137, 137, 0.3)" }; // 红色
    } else if (row.returnDate && moment(row.returnDate).isBefore(row.dueDate)) {
      return { backgroundColor: "rgba(133, 206, 97, 0.3)" }; // 绿色
    } else if (!row.returnDate && moment().isAfter(row.dueDate)) {
      return { backgroundColor: "rgba(235, 181, 99, 0.3)" }; // 黄色
    }
  } else if (column.property === "paymentStatus") {
    if (row.paymentStatus === "未缴款") {
      return { backgroundColor: "rgba(247, 137, 137, 0.3)" }; // 红色
    } else if (row.paymentStatus === "已缴款") {
      return { backgroundColor: "rgba(133, 206, 97, 0.3)" }; // 绿色
    }
  } else if (column.property === "renewalStatus") {
    if (row.renewalStatus === "可续借") {
      return { backgroundColor: "rgba(133, 206, 97, 0.3)" }; // 绿色
    } else if (row.renewalStatus === "不可续借") {
      return { backgroundColor: "rgba(247, 137, 137, 0.3)" }; // 红色
    }
  }
  return {};
};

const fineFormatter = (row, column, cellValue) => {
  return cellValue === null ? "无需缴款" : cellValue;
};

const remindBorrower = async (email) => {
  ElMessageBox.confirm("此操作将发送邮件到此用户的邮箱上, 是否继续?", "提示", {
    confirmButtonText: "确定",
    cancelButtonText: "取消",
    type: "warning",
  })
    .then(async () => {
      let remindResult = await mailService(email);
      if (remindResult.code === 0) {
        ElMessage.success("发送成功");
      } else {
        ElMessage.error("发送失败");
      }
    })
    .catch(() => {
      ElMessage.error("发送失败");
    });
};

const confirmBatchRemind = () => {
  ElMessageBox.confirm("此操作将发送邮件到选中的用户, 是否继续?", "提示", {
    confirmButtonText: "确定",
    cancelButtonText: "取消",
    type: "warning",
  })
    .then(async () => {
      let successCount = 0;
      let skipCount = 0;
      for (const borrow of selectedBorrows.value) {
        let remindResult = await mailService(borrow.email);
        if (remindResult.code === 0) {
          successCount++;
        } else {
          skipCount++;
        }
      }
      ElMessage.success(`发送成功: ${successCount}, 跳过: ${skipCount}`);
    })
    .catch(() => {
      ElMessage.info("已取消发送邮件");
    });
};

const filterHandler = (value, row, column) => {
  const property = column.property;
  return row[property] === value;
};

listBorrows();
</script>

<template>
  <div class="search-container">
    <el-input
      v-model="searchBorrow.borrowingId"
      placeholder="请输入借阅ID"
      clearable
      class="search-input"
      type="number"
      :min="1"
    />
    <el-input
      v-model="searchBorrow.bookId"
      placeholder="请输入书籍ID"
      clearable
      class="search-input"
      type="number"
      :min="1"
    />
    <el-input
      v-model="searchBorrow.studentId"
      placeholder="请输入学号"
      clearable
      class="search-input"
      type="number"
      :min="1"
    />
    <el-input
      v-model="searchBorrow.studentName"
      placeholder="请输入学生姓名"
      clearable
      class="search-input"
    />
    <el-input
      v-model="searchBorrow.categoryName"
      placeholder="请输入读者类别"
      clearable
      class="search-input"
    />
    <el-input
      v-model="searchBorrow.renewalStatus"
      placeholder="请输入续借状态"
      clearable
      class="search-input"
    />
  </div>
  <div class="button-group">
    <div class="extra-buttons">
      <el-button
        type="danger"
        @click="confirmBatchDelete"
        icon="RemoveFilled"
        :disabled="selectedBorrows.length === 0"
        >批量删除</el-button
      >
      <el-button
        type="primary"
        @click="confirmExtendDueDates(30)"
        icon="Moon"
        :disabled="selectedBorrows.length === 0"
        >寒假到期日期推迟</el-button
      >
      <el-button
        type="primary"
        @click="confirmExtendDueDates(60)"
        icon="Sunny"
        :disabled="selectedBorrows.length === 0"
        >暑假到期日期推迟</el-button
      >
      <el-button
        type="primary"
        @click="confirmBatchRemind"
        icon="Bell"
        :disabled="selectedBorrows.length === 0"
        >批量催还</el-button
      >
    </div>
    <el-button @click="listBorrows" type="primary" icon="Search"
      >搜索</el-button
    >
    <el-button @click="reset" type="warning" icon="RefreshRight"
      >重置</el-button
    >
  </div>

  <el-table
    :data="borrowsData"
    :cell-style="statusCellStyle"
    :header-cell-style="{ background: '#2a598a', color: '#ffffff' }"
    border
    stripe
    :max-height="500"
    style="width: 100%"
    highlight-current-row
    @selection-change="handleSelectionChange"
  >
    <el-table-column type="selection" width="40"></el-table-column>
    <el-table-column
      fixed
      sortable
      prop="borrowingId"
      label="借阅ID"
      width="120"
    />
    <el-table-column
      fixed
      sortable
      prop="studentName"
      label="学生姓名"
      width="120"
    />
    <el-table-column sortable prop="studentId" label="学号" min-width="120" />
    <el-table-column sortable prop="bookId" label="图书ID" min-width="120" />
    <el-table-column sortable prop="bookName" label="书名" min-width="120" />
    <el-table-column
      sortable
      prop="categoryName"
      label="读者类别"
      min-width="120"
    />
    <el-table-column
      min-width="120"
      sortable
      prop="borrowDate"
      label="借阅日期"
      :formatter="formatDate"
    />
    <el-table-column
      min-width="120"
      sortable
      prop="dueDate"
      label="到期日期"
      :formatter="formatDate"
    />
    <el-table-column
      min-width="120"
      sortable
      prop="returnDate"
      label="归还日期"
      :formatter="formatDate"
    />
    <el-table-column
      sortable
      prop="renewalStatus"
      label="续借状态"
      min-width="120"
    />
    <el-table-column
      min-width="120"
      sortable
      prop="totalAmount"
      label="缴款金额"
      :formatter="fineFormatter"
    />
    <el-table-column
      min-width="130"
      sortable
      prop="paymentStatus"
      label="缴款状态"
      :formatter="fineFormatter"
      :filters="[
        { text: '已缴款', value: '已缴款' },
        { text: '未缴款', value: '未缴款' },
      ]"
      :filter-method="filterHandler"
    />
    <el-table-column label="催还" align="center" fixed="right" width="110">
      <template #default="scope">
        <el-button
          v-if="!scope.row.returnDate && moment().isAfter(scope.row.dueDate)"
          type="primary"
          @click="remindBorrower(scope.row.email)"
          icon="Bell"
          >催还</el-button
        >
      </template>
    </el-table-column>
    <el-table-column label="操作" align="center" fixed="right" width="200">
      <template #default="scope">
        <el-button type="warning" @click="viewUpdate(scope.row)" icon="Refresh"
          >更新</el-button
        >
        <el-button
          type="danger"
          @click="confirmDelete(scope.row.borrowingId)"
          icon="delete"
          >删除</el-button
        >
      </template>
    </el-table-column>
  </el-table>

  <el-pagination
    v-model:current-page="pageNum"
    v-model:page-size="pageSize"
    :page-sizes="[5, 10, 15, 20, 30, 50, 100]"
    background
    layout="total, sizes, prev, pager, next, jumper"
    :total="total"
    @size-change="handleSizeChange"
    @current-change="handleCurrentChange"
    style="margin-top: 20px; justify-content: flex-end"
  />

  <el-dialog title="更新借阅信息" v-model="showUpdateDialog" width="500">
    <el-form :model="newBorrow" :rules="rulesUpdate" ref="updateFormRef">
      <el-form-item label="书籍ID" prop="bookId">
        <el-input v-model="newBorrow.bookId" disabled></el-input>
      </el-form-item>
      <el-form-item label="用户ID" prop="userId">
        <el-input v-model="newBorrow.userId" disabled></el-input>
      </el-form-item>
      <el-form-item label="借阅日期" prop="borrowDate">
        <el-date-picker
          v-model="newBorrow.borrowDate"
          type="date"
          placeholder="请选择借阅日期"
          format="YYYY-MM-DD"
          value-format="YYYY-MM-DD"
        />
      </el-form-item>
      <el-form-item label="归还日期" prop="returnDate">
        <el-date-picker
          v-model="newBorrow.returnDate"
          type="date"
          placeholder="请选择归还日期"
          format="YYYY-MM-DD"
          value-format="YYYY-MM-DD"
        />
      </el-form-item>
      <el-form-item label="续借状态" prop="renewalStatus">
        <el-input v-model="newBorrow.renewalStatus" disabled></el-input>
      </el-form-item>
      <el-form-item label="到期日期" prop="dueDate">
        <el-date-picker
          v-model="newBorrow.dueDate"
          type="date"
          placeholder="请选择到期日期"
          format="YYYY-MM-DD"
          value-format="YYYY-MM-DD"
        />
      </el-form-item>
      <el-form-item label="缴款状态" prop="paymentStatus">
        <el-select
          v-model="newBorrow.paymentStatus"
          placeholder="请选择"
          :disabled="!newBorrow.paymentStatus"
        >
          <el-option label="已缴款" value="已缴款"></el-option>
          <el-option label="未缴款" value="未缴款"></el-option>
        </el-select>
      </el-form-item>
    </el-form>
    <span slot="footer" class="dialog-footer">
      <el-button @click="showUpdateDialog = false">取消</el-button>
      <el-button type="primary" @click="updateBorrow">确定</el-button>
    </span>
  </el-dialog>
</template>

<style scoped></style>
